import { getPage, getImage } from '../../utils/config';
import api from '../../utils/api';
import { http, promisify, $toast } from '../../utils/utils';
import wxApi from '../../utils/wxApi';
const app = getApp();

Page({

    /**
     * 页面的初始数据
     */
    data: {
        getImage: getImage,
        loading: 0,
        orderId: 0,
        userId: 0,
        orderInfo: {},
        timesDays: 0,
        timesHours: 0,
        timesMinute: 0, 
        timesSecond: 0,
    },

    /**
     * build tips
     */
    building() {
        $toast(`功能开发中`)
    },

    /**
     * 复制订单
     */
    copyClick(e) {
        const { txt } = e.currentTarget.dataset || e.target.dataset;
        wx.setClipboardData({
            data: txt,
        });
    },

    /**
     * 呼叫卖家
     */
    callSellerClick(e) {
        const { phone } = e.currentTarget.dataset || e.target.dataset;
        wx.makePhoneCall({
            phoneNumber: phone,
        })
    },

    /**
     * 跳转店铺--路由跳转
     */
    jumpShopClick(e) {
        const { id } = e.currentTarget.dataset || e.target.dataset;
        wxApi.navigateTo(getPage.shop, { id: id })
    },

    /**
     * 跳转商品--路由跳转
     */
    jumpGoodsClick(e) {
        const { id } = e.currentTarget.dataset || e.target.dataset;
        wxApi.navigateTo(getPage.goods, { id: id })
    },

    /**
     * 退款/退货
     */
    applyRefundClick(e) {
        const { dataset } = e.currentTarget || e.target;
        const { orderInfo, userId } = this.data;
        const pageUrl = dataset.mode == 1 ? getPage.applyRefund : getPage.applySelectType;
        const item = orderInfo.order_items[dataset.id].item;
        const data = {
            userId: userId,
            products: JSON.stringify({
                mobile: orderInfo.info[0].mobile,
                orderid: orderInfo.info[0].orderid,
                item_id: item.item_id,
                ordernum: item.ordernum,
                shop_price: item.shop_price,
                product_attr: item.product_attr,
                productname: item.productname,
                product_img: item.product_img,
            }),
        }

        if(dataset.mode == 1){
            data.source = 1
        }

        wxApi.navigateTo(pageUrl, data);
    },

    /**
     * 退款退货--路由调用
     */
    applyRefund(id) {
        if (this.pages !== undefined || this.pages !== null) {
            this.pages.applyRefund(id, (res) => {
                this.setData({ orderInfo: this.orderDataModify(res) });
            });
        }
    },

    /**
     * 查看售后
     */
    aftersaleClick(e) {
        const { dataset } = e.currentTarget || e.target;
        wxApi.navigateTo(getPage.aftersaleDetails, {
            id: dataset.id,
            source: 1,
        })
    },

    /**
     * 删除订单
     */
    deleteOrderClick(e) {
        const that = this;

        promisify(wx.showModal)({
            content: '确认删除订单',
        }).then((res) => {
            if (res.confirm) {
                wx.navigateBack({
                    delta: 1,
                    success() {
                        if (that.pages !== undefined || that.pages !== null)
                            that.pages.deleteOrder(e);
                    }  
                })
            }
        })
    },

    /**
     * 取消订单
     */
    cancelOrderClick(e) {
        promisify(wx.showModal)({
            content: '确认取消订单'
        }).then((res) => {
            if (res.confirm) {
                if (this.pages !== undefined || this.pages !== null){
                    this.pages.cancelOrder(e, (res) => {
                        this.setData({ orderInfo: this.orderDataModify(res) });
                    });
                }
            }
        });
    },

    /**
     * 确认收货
     */
    confirmOrderClick(e) {
        promisify(wx.showModal)({
            content: '是否确认收货'
        }).then((res) => {
            if (res.confirm) {
                if (this.pages !== undefined || this.pages !== null) {
                    this.pages.confirmOrder(e, (res) => {
                        this.setData({ orderInfo: this.orderDataModify(res) });
                    });
                }
            }
        })
    },

    /**
     * 查看物流
     */
    jumpShippingClick(e) {
        const { dataset } = e.currentTarget || e.target;
        wxApi.navigateTo(getPage.orderExpress, {
            orderId: dataset.orderId,
            tracknum: dataset.tracknum,
            shippingName: dataset.shippingName,
            shipping: dataset.shipping,
        });
    },

    /**
     * 去付款
     */
    paymentClick(e) {
        const { dataset } = e.currentTarget || e.target;
        const { orderInfo } = this.data;

        wxApi.navigateTo(getPage.checkout, {
            source: 2,
            orderId: orderInfo.info[0].orderid,
            orderSn: orderInfo.info[0].ordersn,
            sumPrice: orderInfo.info[0].order_amount,
            sumShippingfee: orderInfo.info[0].shipping_fee,
            sumGoodsPrice: orderInfo.info[0].goods_amount,
            address: JSON.stringify({
                consignee: orderInfo.info[0].consignee,
                mobile: orderInfo.info[0].mobile,
                areaname: orderInfo.info[0].address1,
                address: orderInfo.info[0].address2,
            }),
        });
    },

    /**
     * 付款成功
     */
    paymentUpdate(id) {
        if (this.pages !== undefined || this.pages !== null) {
            this.pages.paymentUpdate(id, (res) => {
                this.setData({ orderInfo: this.orderDataModify(res) });
            });
        }
    },

    /**
     * 评价
     */
    commentsClick(e) {
        const { id } = e.currentTarget.dataset || e.target.dataset;
        const { orderInfo } = this.data;
        let pageUrl = id == 0 ? getPage.commentsEdit : getPage.commentsAppend;
        let products = [];

        orderInfo.order_items.forEach((item) => {
            products.push({
                commentId: item.item.commentid,
                itemId: item.item.item_id,
                pic: item.item.product_img,
                title: item.item.productname
            });
        });

        wxApi.navigateTo(pageUrl, {
            products: JSON.stringify(products),
            shopName: orderInfo.info[0].ShopName,
            orderId: orderInfo.info[0].orderid,
        });
    },

    /**
     * 评价成功
     */
    commentsOrder(id) {
        if (this.pages !== undefined || this.pages !== null) {
            this.pages.commentsOrder(id, (res) => {
                this.setData({ orderInfo: this.orderDataModify(res) });
            });
        }
    },

    /**
     * 追评成功
     */
    appendCommentsOrder(id) {
        if (this.pages !== undefined || this.pages !== null) {
            this.pages.appendCommentsOrder(id, (res) => {
                this.setData({ orderInfo: this.orderDataModify(res) });
            });
        }
    },

    /**
     * 订单数据模型调整
     */
    orderDataModify(data) {
        
        //订单操作按钮显示
        let operatButton = {
            buttonFix: false,
            cancelOrder: false,
            deleteOrder: false,
            paymentOrder: false,
            viewPost: false,
            confirmOrder: false,
        }

        let info = data.info[0];
        //是否显示"取消订单"
        if (info.order_status == 0) {
            operatButton.cancelOrder = true
        }
        //是否显示"去付款"
        if (info.pay_status == 0 && info.trade_status == 1) {
            operatButton.paymentOrder = true
        }
        //是否显示"删除订单"
        if (info.trade_status == 2 || info.trade_status == 3) {
            operatButton.deleteOrder = true
        }
        //是否显示"查看物流"
        if (info.shipping_status == 1 || info.shipping_status == 2) {
            operatButton.viewPost = true
        }
        //是否显示"确认收货"
        if (info.order_status == 1 && info.shipping_status == 1) {
            operatButton.confirmOrder = true
        }
        //订单商品总数
        data.order_items.forEach((item) => {
            let operat = {
                afReturns: false,
                afComplaint: false,
                afRefund: false,
                afDetails: false,
            }

            //有售后就不显示"确认收货"
            if (item.af.Order_Status == 0) {
                operatButton.confirmOrder = false;
            }

            //商品付款后操作
            //没有售后
            if (item.af.ID == 0) {
                //申请退换货
                if (info.pay_status == 2 && info.shipping_status == 1) {
                    operat.afReturns = true;
                    //投诉商家
                } else if (info.pay_status == 2 && info.shipping_status == 2 && info.trade_status == 2) {
                    operat.afComplaint = true;
                    //申请退款
                } else if (info.pay_status == 2 && info.shipping_status == 0 && info.trade_status == 1) {
                    operat.afRefund = true;
                }
                //有售后
            } else if (item.af.ID > 0) {
                //查看售后
                operat.afDetails = true;
            }

            item.operat = operat;
        });
        //是否显示浮动按钮
        if (!operatButton.cancelOrder && !operatButton.deleteOrder && !operatButton.paymentOrder && !operatButton.viewPost && !operatButton.confirmOrder && !data.isshowcomment && !data.isshowzhuijia) {
            operatButton.buttonFix = true
        }

        //页面状态
        let status = {
            name: '',
            image: '',
            code: -1,
        }
        if (info.trade_status == 1) {
            if (info.shipping_status == 0 && info.pay_status == 2) {
                status.name = '已付款';
                status.image = getImage.orderPaid;
                status.code = 1;
            } else if (info.shipping_status == 1 && info.pay_status == 2) {
                status.name = '已发货';
                status.image = getImage.orderExpress;
                status.code = 2;

                //倒计时
                this.setCountDown(data.enddate);
            } else if (info.shipping_status == 0 && info.pay_status == 0) {
                status.name = '等待付款';
                status.image = getImage.orderPayment;
                status.code = 3;

                //倒计时
                this.setCountDown(data.enddate);
            }
        } else if (info.trade_status == 2) {
            status.name = '交易成功';
            status.image = getImage.orderDone;
            status.code = 4;
        } else if (info.trade_status == 3) {
            status.name = '交易关闭';
            status.image = getImage.orderClose;
            status.code = 5;
        }

        //数据修改
        data.operat = operatButton;
        data.status = status;
        return data;
    },

    /**
     * 等待付款--倒计时
     */
    setCountDown(endTime) {
        let times = (new Date(endTime.replace(/-/g, '/')).getTime() - new Date().getTime()) / 1000;
        let { timesDays, timesHours, timesMinute, timesSecond } = this.data;
        const timer = setInterval(() => {

            //先减去默认1秒
            times--;

            //如果倒计时大于零
            if (times > 0) {
                timesDays = Math.floor(times / (60 * 60 * 24));
                timesHours = Math.floor(times / (60 * 60)) - (timesDays * 24);
                timesMinute = Math.floor(times / 60) - (timesDays * 24 * 60) - (timesHours * 60);
                timesSecond = Math.floor(times) - (timesDays * 24 * 60 * 60) - (timesHours * 60 * 60) - (timesMinute * 60);
            } else {
                timesDays = 0;
                timesHours = 0;
                timesMinute = 0;
                timesSecond = 0;
                clearInterval(timer);
            }

            this.setData({ timesDays, timesHours, timesMinute, timesSecond });
        }, 1000);
    },

    /**
     * 获取订单详情--网络请求
     */
    getOrderDetailsInfo(cb, a = false) {
        const { userId, orderId } = this.data;
        
        http.post(api.default, {
            data: {
                action: 'orderdetail',
                userid: userId,
                id: orderId
            }
        }, a).then((res) => {
            const { data } = res.data;
            this.setData({ orderInfo: this.orderDataModify(data) });
            cb && cb(res);
        }).catch((res) => {
            if(res && res.data.errmsg == '订单已删除'){
                this.setData({
                    loading: 2
                })
            }
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        
        /**
         * 页面参数
         */
        if(JSON.stringify(options) !== '{}'){
            this.setData({
                orderId: options.id
            })
        }
        
        //上一个页面路由
        this.pages = getCurrentPages()[getCurrentPages().length - 2];

        /**
         * 获取用户
         */
        app.getLogin().then((res) => {
            const { user } = res.data;
            this.setData({ 
                userId: user.user_id
             });

            this.getOrderDetailsInfo(() => {
                this.setData({ loading: 1 })
            });
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.getOrderDetailsInfo(() => {
            wx.stopPullDownRefresh();
        }, true);
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    }
})